package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.dao.*;
import com.changgou.goods.pojo.*;
import com.changgou.goods.service.SpuService;
import com.changgou.util.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    @Autowired
    private SkuMapper skuMapper;

    /**
     * 查询全部列表
     *
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @Override
    public Goods findById(String id) {
        //查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //根据spuid查询skuList
        /*
            Example自定义的类，目的就是为了封装条件，
            封装的条件是对应sku实体类中的属性
         */
        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId", id);
        List<Sku> skuList = skuMapper.selectByExample(example);
        //封装数据
        Goods goods = new Goods();
        goods.setSpu(spu);
        goods.setSkuList(skuList);
        return goods;
    }


    /**
     * 增加
     *
     * @param goods
     */
    @Override
    public void add(Goods goods) {
        //新增spu
        Spu spu = goods.getSpu();
        long id = idWorker.nextId();
        spu.setId(String.valueOf(id));//设置主键
        spu.setIsDelete("0");//是否删除,0未删除
        spu.setIsMarketable("0");//是否上架,0未上架
        spu.setStatus("0");//审核状态,0未审核
        spuMapper.insertSelective(spu);

        //新增sku列表
        saveSkuList(goods);
    }


    /**
     * 保存sku列表
     *
     * @param goods
     */
    private void saveSkuList(Goods goods) {
        //获得skulist
        List<Sku> skuList = goods.getSkuList();
        if (skuList != null) {
            for (Sku sku : skuList) {
                //获取spu对象
                Spu spu = goods.getSpu();
                //生命日期
                Date date = new Date();
                //通过spu中的三级菜单id获取category分类实体
                Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());
                //通过spu中的品牌id获取brand实体
                Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
                //添加分类和品牌添加到tb_category_brand表中
                CategoryBrand categoryBrand = new CategoryBrand();
                categoryBrand.setBrandId(brand.getId());
                categoryBrand.setCategoryId(category.getId());
                //根据当前分类id和品牌id查询是否已经存在
                int count = categoryBrandMapper.selectCount(categoryBrand);
                if (count == 0) {//不存在
                    //则添加
                    categoryBrandMapper.insert(categoryBrand);
                }
                //1.设置sku主键
                sku.setId(String.valueOf(idWorker.nextId()));
                //2.设置spec规格,因为数据库表字段里面是JSON,所以如果为null或空串的话把他设置成空的JSON{}
                if (sku.getSpec() == null || "".equals(sku.getSpec())) {
                    sku.setSpec("{}");
                }
                /*
                     3.设置sku的名称，sku名称=spu名称+规格
                     spe={'颜色': '红色', '版本': '8GB+128GB'}
                    第一次遍历 name=spu名称 红色
                    第二次遍历 name= spu名称 红色 8GB+128GB
                 */
                String spuName = spu.getName();
                Map<String, String> specMap = JSON.parseObject(sku.getSpec(), Map.class);
                if (specMap != null || specMap.size() > 0) {
                    for (String value : specMap.values()) {
                        spuName += " " + value;//spuName = " " + value 把spec里面的元素拼接在spuName后面
                    }
                }
                sku.setName(spuName);
                //4.设置spuId
                sku.setSpuId(spu.getId());
                //5.设置时间
                sku.setCreateTime(date);
                sku.setUpdateTime(date);
                //6.设置分类id和分类名称，注意该分类是spu表中的三级分类id获取的
                sku.setCategoryId(category.getId());
                sku.setCategoryName(category.getName());
                //7.设置品牌名称
                sku.setBrandName(brand.getName());
                //8.循环添加sku
                skuMapper.insertSelective(sku);
            }
        }
    }


    /**
     * 修改
     *
     * @param goods
     */
    @Override
    public void update(Goods goods) {
        //1.修改spu
        Spu spu = goods.getSpu();
        if (spu.getId() != null) {
            spuMapper.updateByPrimaryKeySelective(spu);
        }
        //2.修改sku
        //2.1要删除skuList列表
        System.out.println(spu.getId() + "=============================================");
        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId", spu.getId());
        skuMapper.deleteByExample(example);
        //2.2然后重新添加sku列表
        this.saveSkuList(goods);
    }

    /**
     * 商品审核
     *
     * @param id
     */
    public void audit(String id) {
        //查询spu对象
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //判断商品是否存在
        if (spu == null) {
            throw new RuntimeException("商品不存在");
        }
        //判断商品是否被删除
        if ("1".equals(spu.getIsDelete())) {
            throw new RuntimeException("商品已经被删除");
        }
        spu.setStatus("1");//修改审核状态为1,表示已经通过审核
        spu.setIsMarketable("1");//自动上架
        spuMapper.updateByPrimaryKeySelective(spu);

    }


    /**
     * 逻辑删除
     *
     * @param id
     */
    @Transactional
    @Override
    public void delete(String id) {
        //查询spu对象
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //必须先下架才能删除
        if (!"0".equals(spu.getIsMarketable())){
            throw new RuntimeException("必须先下架才能删除");
        }
        spu.setIsDelete("1");//逻辑删除
        spu.setStatus("0");//未审核状态
        spuMapper.updateByPrimaryKeySelective(spu);
    }


    /**
     * 条件查询
     *
     * @param searchMap
     * @return
     */
    @Override
    public List<Spu> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Spu> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        return (Page<Spu>) spuMapper.selectAll();
    }

    /**
     * 条件+分页查询
     *
     * @param searchMap 查询条件
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @Override
    public Page<Spu> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        return (Page<Spu>) spuMapper.selectByExample(example);
    }



    /**
     * 还原逻辑删除的商品
     * @param id
     */
    @Override
    public void restore(String id) {
        //查询spu对象
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (!"1".equals(spu.getIsDelete())){
            throw  new RuntimeException("此商品未删除！");
        }
        spu.setIsDelete("0");
        spu.setStatus("0");//未审核
        spuMapper.updateByPrimaryKeySelective(spu);
    }


    /**
     * 物理删除
     * @param id
     */
    @Transactional
    @Override
    public void realDelete(String id) {
        //查询spu对象
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (!"1".equals(spu.getIsDelete())){
            throw  new RuntimeException("此商品未删除！");
        }
        spuMapper.deleteByPrimaryKey(spu);
    }


    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @Override
    public Spu findSpuById(String id) {
        //查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        return spu;
    }

    /**
     * 构建查询对象
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 主键
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andEqualTo("id", searchMap.get("id"));
            }
            // 货号
            if (searchMap.get("sn") != null && !"".equals(searchMap.get("sn"))) {
                criteria.andEqualTo("sn", searchMap.get("sn"));
            }
            // SPU名
            if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                criteria.andLike("name", "%" + searchMap.get("name") + "%");
            }
            // 副标题
            if (searchMap.get("caption") != null && !"".equals(searchMap.get("caption"))) {
                criteria.andLike("caption", "%" + searchMap.get("caption") + "%");
            }
            // 图片
            if (searchMap.get("image") != null && !"".equals(searchMap.get("image"))) {
                criteria.andLike("image", "%" + searchMap.get("image") + "%");
            }
            // 图片列表
            if (searchMap.get("images") != null && !"".equals(searchMap.get("images"))) {
                criteria.andLike("images", "%" + searchMap.get("images") + "%");
            }
            // 售后服务
            if (searchMap.get("saleService") != null && !"".equals(searchMap.get("saleService"))) {
                criteria.andLike("saleService", "%" + searchMap.get("saleService") + "%");
            }
            // 介绍
            if (searchMap.get("introduction") != null && !"".equals(searchMap.get("introduction"))) {
                criteria.andLike("introduction", "%" + searchMap.get("introduction") + "%");
            }
            // 规格列表
            if (searchMap.get("specItems") != null && !"".equals(searchMap.get("specItems"))) {
                criteria.andLike("specItems", "%" + searchMap.get("specItems") + "%");
            }
            // 参数列表
            if (searchMap.get("paraItems") != null && !"".equals(searchMap.get("paraItems"))) {
                criteria.andLike("paraItems", "%" + searchMap.get("paraItems") + "%");
            }
            // 是否上架
            if (searchMap.get("isMarketable") != null && !"".equals(searchMap.get("isMarketable"))) {
                criteria.andEqualTo("isMarketable", searchMap.get("isMarketable"));
            }
            // 是否启用规格
            if (searchMap.get("isEnableSpec") != null && !"".equals(searchMap.get("isEnableSpec"))) {
                criteria.andEqualTo("isEnableSpec", searchMap.get("isEnableSpec"));
            }
            // 是否删除
            if (searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete"))) {
                criteria.andEqualTo("isDelete", searchMap.get("isDelete"));
            }
            // 审核状态
            if (searchMap.get("status") != null && !"".equals(searchMap.get("status"))) {
                criteria.andEqualTo("status", searchMap.get("status"));
            }

            // 品牌ID
            if (searchMap.get("brandId") != null) {
                criteria.andEqualTo("brandId", searchMap.get("brandId"));
            }
            // 一级分类
            if (searchMap.get("category1Id") != null) {
                criteria.andEqualTo("category1Id", searchMap.get("category1Id"));
            }
            // 二级分类
            if (searchMap.get("category2Id") != null) {
                criteria.andEqualTo("category2Id", searchMap.get("category2Id"));
            }
            // 三级分类
            if (searchMap.get("category3Id") != null) {
                criteria.andEqualTo("category3Id", searchMap.get("category3Id"));
            }
            // 模板ID
            if (searchMap.get("templateId") != null) {
                criteria.andEqualTo("templateId", searchMap.get("templateId"));
            }
            // 运费模板id
            if (searchMap.get("freightId") != null) {
                criteria.andEqualTo("freightId", searchMap.get("freightId"));
            }
            // 销量
            if (searchMap.get("saleNum") != null) {
                criteria.andEqualTo("saleNum", searchMap.get("saleNum"));
            }
            // 评论数
            if (searchMap.get("commentNum") != null) {
                criteria.andEqualTo("commentNum", searchMap.get("commentNum"));
            }

        }
        return example;
    }

}
